<template>
  <div>
    <div class="q-pa-md row justify-center">
      <t-input
        style="min-width: 10em"
        type="number"
        v-model.number="virtualListIndex"
        :min="0"
        :max="9999"
        label="Scroll to index"
        input-class="text-right"
        outlined
      />
      <t-btn
        class="q-ml-sm"
        label="Go"
        no-caps
        color="primary"
        @click="executeScroll"
      />
    </div>

    <t-separator />

    <t-virtual-scroll
      ref="virtualListRef"
      style="max-height: 300px"
      component="q-list"
      :items="heavyList"
      separator
      @virtual-scroll="onVirtualScroll"
      v-slot="{ item, index }"
    >
      <t-item
        :key="index"
        dense
        :class="{ 'bg-black text-white': index === virtualListIndex }"
      >
        <t-item-section>
          <t-item-label> #{{ index }} - {{ item.label }} </t-item-label>
        </t-item-section>
      </t-item>
    </t-virtual-scroll>
  </div>
</template>

<script>
  import { onMounted, ref } from 'vue';

  const maxSize = 10000;
  const heavyList = [];

  for (let i = 0; i < maxSize; i++) {
    heavyList.push({
      label: 'Option ' + (i + 1),
    });
  }

  export default {
    setup() {
      const virtualListRef = ref(null);
      const virtualListIndex = ref(1200);

      onMounted(() => {
        virtualListRef.value.scrollTo(virtualListIndex.value);
      });

      return {
        heavyList,
        virtualListRef,
        virtualListIndex,

        onVirtualScroll({ index }) {
          virtualListIndex.value = index;
        },

        executeScroll() {
          virtualListRef.value.scrollTo(virtualListIndex.value, 'start-force');
        },
      };
    },
  };
</script>
